<template>
  <div class="spots-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
              景点导览
            </h1>
            <p class="text-gray-600 dark:text-gray-400 mt-2">
              探索贵港特色景点，规划您的完美行程
            </p>
          </div>
          <div class="flex items-center space-x-4">
            <el-button
              type="primary"
              class="flex items-center"
              @click="$router.push('/ai-chat')"
            >
              <el-icon class="mr-1"><ChatLineRound /></el-icon>
              AI智能助手
            </el-button>
            <el-button class="back-btn" @click="router.back()">
              <el-icon class="mr-1"><Back /></el-icon>
              返回上一页
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <!-- 知识图谱 -->
      <div
        class="knowledge-graph-container bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4 mb-6"
      >
        <div class="h-[360px]">
          <KnowledgeGraph @add-to-route="handleAddToRoute" />
        </div>
      </div>

      <!-- 筛选工具栏 -->
      <div class="filter-toolbar bg-white rounded-lg shadow-sm p-4 mb-6">
        <!-- 搜索栏 -->
        <div class="search-bar mb-4">
          <el-input
            v-model="searchQuery"
            placeholder="搜索景点名称、地址或关键词"
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <!-- 景区分类 -->
          <div class="filter-item">
            <el-select
              v-model="filters.category"
              placeholder="景区分类"
              clearable
              class="w-full"
            >
              <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <!-- 区域选择 -->
          <div class="filter-item">
            <el-select
              v-model="filters.area"
              placeholder="区域选择"
              clearable
              class="w-full"
            >
              <el-option
                v-for="item in areaOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <!-- 特色标签 -->
          <div class="filter-item">
            <el-select
              v-model="filters.tags"
              placeholder="特色标签"
              multiple
              collapse-tags
              collapse-tags-tooltip
              class="w-full"
            >
              <el-option
                v-for="item in tagOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <!-- 排序方式 -->
          <div class="filter-item">
            <el-select
              v-model="filters.sort"
              placeholder="排序方式"
              class="w-full"
            >
              <el-option
                v-for="item in sortOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>

        <!-- 已选条件 -->
        <div v-if="selectedFilters.length > 0" class="selected-filters mt-4">
          <el-tag
            v-for="filter in selectedFilters"
            :key="filter.value"
            closable
            class="mr-2"
            @close="removeFilter(filter)"
          >
            {{ filter.label }}
          </el-tag>
        </div>
      </div>

      <div class="main-content-grid grid grid-cols-12 gap-6">
        <!-- 左侧主要内容 -->
        <div class="main-content col-span-12 lg:col-span-8">
          <!-- 工具栏 -->
          <div class="view-controls flex justify-between items-center mb-6">
            <div class="left-controls flex items-center space-x-4">
              <div class="total-count text-gray-600">
                共找到
                <span class="text-primary-600 font-medium">{{
                  totalCount
                }}</span>
                个景点
              </div>
              <el-button type="primary" @click="showRoutePlanner">
                <el-icon><Position /></el-icon>
                路线规划
              </el-button>
            </div>
            <div class="view-switcher">
              <el-radio-group v-model="viewMode" size="large">
                <el-radio-button label="grid">
                  <el-icon><Grid /></el-icon>
                </el-radio-button>
                <el-radio-button label="map">
                  <el-icon><Location /></el-icon>
                </el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <!-- 景点列表 -->
          <div class="spots-list">
            <!-- 网格视图 -->
            <div v-if="viewMode === 'grid'" class="grid-view">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div
                  v-for="spot in spotsList"
                  :key="spot.id"
                  class="spot-card bg-white rounded-lg shadow-sm overflow-hidden cursor-pointer hover:shadow-md transition-shadow"
                  @click="viewSpotDetail(spot.id)"
                >
                  <!-- 景点封面 -->
                  <div class="relative">
                    <el-image
                      :src="spot.coverImage || spot.cover"
                      fit="cover"
                      class="w-full h-48 object-cover"
                    >
                      <template #error>
                        <div class="image-slot">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                    <div
                      class="spot-price absolute top-3 right-3 bg-primary-600 text-white px-3 py-1 rounded-full text-sm"
                    >
                      {{ spot.price > 0 ? `¥${spot.price}起` : "免费" }}
                    </div>
                  </div>

                  <!-- 景点信息 -->
                  <div class="p-4">
                    <h3 class="text-lg font-medium mb-2">{{ spot.name }}</h3>

                    <div class="spot-rating flex items-center mb-2">
                      <el-rate
                        :model-value="spot.rating || 4.5"
                        disabled
                        text-color="#ff9900"
                      />
                      <span class="text-orange-500 ml-2"
                        >{{ spot.rating || 4.5 }}分</span
                      >
                    </div>

                    <div class="spot-tags mb-2" v-if="spot.tags && spot.tags.length">
                      <el-tag
                        v-for="tag in spot.tags"
                        :key="tag"
                        :type="getTagType(tag)"
                        size="small"
                        class="mr-1"
                      >
                        {{ tag }}
                      </el-tag>
                    </div>
                    <div class="spot-tags mb-2" v-else-if="spot.category">
                      <el-tag
                        :type="getTagType(getCategoryName(spot.category))"
                        size="small"
                        class="mr-1"
                      >
                        {{ getCategoryName(spot.category) }}
                      </el-tag>
                    </div>

                    <div
                      class="spot-desc text-gray-600 text-sm line-clamp-2 mb-2"
                    >
                      {{ spot.description }}
                    </div>

                    <div
                      class="spot-meta flex items-center text-sm text-gray-500"
                    >
                      <span class="location flex items-center">
                        <el-icon><Location /></el-icon>
                        {{ spot.address || spot.location || '贵港市' }}
                      </span>
                      <span class="visitors ml-4 flex items-center" v-if="spot.visitCount">
                        <el-icon><View /></el-icon>
                        {{ formatNumber(spot.visitCount) }}人去过
                      </span>
                    </div>
                  </div>

                  <!-- 卡片操作 -->
                  <div
                    class="card-actions flex justify-between items-center p-4 border-t border-gray-100"
                  >
                    <div class="left-actions">
                      <el-button
                        :type="isSpotSelected(spot) ? 'primary' : 'default'"
                        @click.stop="toggleSpotSelection(spot)"
                      >
                        {{ isSpotSelected(spot) ? "已选择" : "加入路线" }}
                      </el-button>
                      <el-button
                        type="primary"
                        text
                        @click.stop="$router.push(`/guides?spotId=${spot.id}`)"
                      >
                        查看攻略
                      </el-button>
                    </div>
                    <div class="right-actions space-x-2">
                      <el-button
                        circle
                        :type="spot.isCollected ? 'danger' : 'default'"
                        :icon="spot.isCollected ? 'Star' : 'StarFilled'"
                        @click.stop="toggleCollect(spot)"
                      />
                      <el-button
                        circle
                        :icon="Share"
                        @click.stop="shareSpot(spot)"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 地图视图 -->
            <div v-else class="map-view">
              <MapView
                :markers="spotMarkers"
                :center="mapCenter"
                :zoom="mapZoom"
                class="h-[600px] rounded-lg"
                @marker-click="handleMarkerClick"
              />
            </div>

            <!-- 分页 -->
            <div class="pagination flex justify-center mt-6">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :total="totalCount"
                :page-sizes="[4, 6, 8]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
              />
            </div>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar col-span-12 lg:col-span-4 space-y-6">
          <!-- 推荐景点 -->
          <div class="recommended-spots bg-white rounded-lg shadow-sm p-4">
            <div class="section-header flex justify-between items-center mb-4">
              <h3 class="text-lg font-medium">推荐景点</h3>
              <el-button type="primary" link @click="refreshRecommendations">
                <el-icon><Refresh /></el-icon>
                换一换
              </el-button>
            </div>
            <div class="recommended-list space-y-4">
              <div
                v-for="spot in recommendedSpots"
                :key="spot.id"
                class="recommended-item flex cursor-pointer hover:bg-gray-50 rounded p-2"
                @click="viewSpotDetail(spot.id)"
              >
                <el-image
                  :src="spot.cover"
                  :alt="spot.name"
                  class="w-24 h-24 rounded object-cover"
                />
                <div class="ml-3 flex-1 min-w-0">
                  <div class="font-medium truncate mb-1">{{ spot.name }}</div>
                  <div class="flex items-center mb-1">
                    <el-rate
                      v-model="spot.rating"
                      disabled
                      :max="5"
                      text-color="#ff9900"
                      size="small"
                    />
                    <span class="text-orange-500 text-sm ml-1"
                      >{{ spot.rating }}分</span
                    >
                  </div>
                  <div class="text-sm text-gray-500 line-clamp-2">
                    {{ spot.description }}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 季节推荐 -->
          <div class="seasonal-spots bg-white rounded-lg shadow-sm p-4">
            <div class="section-header mb-4">
              <h3 class="text-lg font-medium">{{ currentSeason }}精选</h3>
              <div class="text-sm text-gray-500 mt-1">当季最佳游玩推荐</div>
            </div>
            <div class="seasonal-list space-y-4">
              <div
                v-for="spot in seasonalSpots"
                :key="spot.id"
                class="seasonal-item bg-gray-50 rounded-lg p-3"
              >
                <el-image
                  :src="spot.cover"
                  :alt="spot.name"
                  class="w-full h-40 rounded-lg object-cover mb-3"
                />
                <h4 class="font-medium mb-2">{{ spot.name }}</h4>
                <p class="text-sm text-gray-600 mb-2">{{ spot.description }}</p>
                <div class="meta-info text-sm text-gray-500">
                  <div class="flex items-center mb-1">
                    <el-icon><Calendar /></el-icon>
                    <span class="ml-1">最佳游玩：{{ spot.bestTime }}</span>
                  </div>
                  <div class="flex items-center">
                    <el-icon><Timer /></el-icon>
                    <span class="ml-1">建议游玩：{{ spot.suggestedTime }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分享对话框 -->
    <ShareDialog
      v-model="shareDialogVisible"
      :content="shareContent"
      @share="handleShare"
    />

    <!-- 攻略生成对话框 -->
    <StrategyDialog
      v-model="strategyDialogVisible"
      :spot="currentSpot"
      @save="handleStrategySave"
    />

    <!-- 路线规划对话框 -->
    <RouteDialog
      v-model="routeDialogVisible"
      :spots="selectedSpots"
      @save="handleRouteSave"
      @map-ready="handleRouteMapReady"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from "vue";
import { useRouter } from "vue-router";
import {
  Grid,
  Location,
  View,
  Share,
  StarFilled,
  Star,
  Calendar,
  Timer,
  Refresh,
  Position,
  Picture,
  ChatLineRound,
  Back,
  Search,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import GlobalCard from "@/components/global/GlobalCard.vue";
import MapView from "@/components/global/MapView.vue";
import ShareDialog from "@/components/global/ShareDialog.vue";
import StrategyDialog from "@/components/spots/StrategyDialog.vue";
import RouteDialog from "@/components/spots/RouteDialog.vue";
import Breadcrumb from "@/components/global/Breadcrumb.vue";
import KnowledgeGraph from "@/components/spots/KnowledgeGraph.vue";
import service from "@/api/axios"; // 导入axios实例

// 添加全局错误处理，拦截地图相关错误
if (typeof window !== 'undefined') {
  // 移除错误通知的MutationObserver
  const removeErrorNotifications = () => {
    const errorNotifications = document.querySelectorAll('.el-notification');
    errorNotifications.forEach(notification => {
      const titleEl = notification.querySelector('.el-notification__title');
      const contentEl = notification.querySelector('.el-notification__content');
      
      if ((titleEl && (
            titleEl.textContent.includes('错误') || 
            titleEl.textContent.includes('Error')
          )) || 
          (contentEl && (
            contentEl.textContent.includes('应用错误') ||
            contentEl.textContent.includes('未捕获的错误') ||
            contentEl.textContent.includes('null')
          ))) {
        notification.style.display = 'none';
        setTimeout(() => {
          notification.remove();
        }, 100);
      }
    });
  };
  
  // 每隔1秒检查一次错误通知并移除
  setInterval(removeErrorNotifications, 1000);
}

const router = useRouter();
const loading = ref(false);

// 搜索相关
const searchQuery = ref("");
const handleSearch = () => {
  // 重置分页
  currentPage.value = 1;
  // 如果搜索框为空，重置所有筛选条件
  if (!searchQuery.value) {
    filters.value = {
      category: "",
      area: "",
      tags: [],
      sort: "rating",
    };
  }
  // 更新筛选条件
  handleFilter();
};

// 监听搜索输入
watch(searchQuery, (newVal) => {
  handleSearch();
});

// 筛选相关
const filters = ref({
  category: "",
  area: "",
  tags: [],
  sort: "rating",
});

// 处理筛选
const handleFilter = async () => {
  loading.value = true;
  try {
    // 构建筛选参数 - 不使用分页参数，获取所有数据
    const params = {
      ...filters.value,
      search: searchQuery.value,
      // 如果后端强制需要分页参数，设置一个很大的值
      pageSize: 1000 // 设置一个足够大的数，确保获取所有数据
    };

    // 调用API获取筛选结果
    const res = await service.get('/public/spot/list', { params });
    console.log("景点列表API响应:", res);
    
    // 打印原始响应数据，查看完整结构
    console.log("完整API响应数据结构:", JSON.stringify(res.data));
    
    let allSpots = [];
    
    // 检查所有可能的数据结构模式
    if (res.data && res.data.content && Array.isArray(res.data.content)) {
      // 直接在res.data中有content数组 - 这是当前API结构
      console.log("从res.data.content直接获取数据");
      allSpots = [...res.data.content];
    } 
    else if (res.data && res.data.code === 200 && res.data.data && res.data.data.content && Array.isArray(res.data.data.content)) {
      // 嵌套在data.data.content
      console.log("从res.data.data.content获取数据");
      allSpots = [...res.data.data.content];
    }
    else if (res.data && res.data.data && res.data.data.records && Array.isArray(res.data.data.records)) {
      // MyBatis-Plus分页格式
      console.log("从res.data.data.records获取数据");
      allSpots = [...res.data.data.records];
    }
    else if (res.data && res.data.data && Array.isArray(res.data.data)) {
      // data直接是数组
      console.log("从res.data.data数组获取数据");
      allSpots = [...res.data.data];
    }
    else if (res.data && Array.isArray(res.data)) {
      // res.data直接是数组
      console.log("从res.data数组获取数据");
      allSpots = [...res.data];
    }
    else {
      console.error("未能识别的API响应格式:", res.data);
      
      // 尝试一种最后的解析方法 - 遍历res.data寻找数组
      if (res.data) {
        for (const key in res.data) {
          if (Array.isArray(res.data[key]) && res.data[key].length > 0) {
            console.log(`找到数组字段: ${key}, 长度: ${res.data[key].length}`);
            if (res.data[key][0] && res.data[key][0].name && res.data[key][0].id) {
              console.log("数组内容有效，使用此数据");
              allSpots = [...res.data[key]];
              break;
            }
          }
        }
      }
    }
    
    // 验证数据
    if (allSpots.length > 0) {
      console.log("成功获取到API数据:", allSpots.length, "条");
      console.log("获取到的景点数据示例:", allSpots.slice(0, 2));
      
      // 将数据保存到状态
      allSpotsList.value = allSpots;
      totalCount.value = allSpots.length;
      
      // 前端分页处理
      updatePagedList();
      
      console.log("处理后的数据:", {
        全部数据长度: allSpotsList.value.length,
        当前页数据长度: spotsList.value.length,
        总数: totalCount.value
      });
    } else {
      console.warn("API返回的数据解析为空，使用测试数据");
      useTestData();
    }
    
    return spotsList.value;
  } catch (error) {
    console.error("获取景点列表失败:", error);
    useTestData();
    return spotsList.value;
  } finally {
    loading.value = false;
  }
};

// 提取测试数据使用逻辑到单独函数
const useTestData = () => {
  // 使用测试数据
  allSpotsList.value = [
    {
      id: 1,
      name: "贵港江滨公园",
      coverImage: "https://img0.baidu.com/it/u=1995709151,1000347016&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500",
      rating: 4.5,
      price: 0,
      category: "water",
      description: "位于贵港市区邕江江畔，是市民休闲娱乐的好去处，园内绿树成荫，设有儿童游乐区、健身区等多个功能区。",
    },
    {
      id: 2, 
      name: "贵港博物馆",
      coverImage: "https://img1.baidu.com/it/u=2689790312,1143352549&fm=253&fmt=auto&app=138&f=JPEG?w=1376&h=500",
      rating: 4.8,
      price: 0,
      category: "museum",
      description: "贵港博物馆是一座综合性地志博物馆，馆内收藏了大量反映贵港历史文化的文物，是了解贵港历史文化的重要场所。"
    },
    {
      id: 3,
      name: "贵港园博园",
      category: "nature", 
      coverImage: "https://img2.baidu.com/it/u=4080716091,1174686661&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=250",
      description: "贵港园博园是一个集园艺展示、科普教育、休闲娱乐于一体的综合性公园，园内种植了数千种植物，四季花开不断。",
      rating: 4.6,
      price: 60
    },
    {
      id: 4,
      name: "贵港古镇",
      category: "historical",
      coverImage: "https://img0.baidu.com/it/u=2330699682,103157205&fm=253&fmt=auto&app=120&f=JPEG?w=1202&h=800",
      description: "保存完好的古镇街区，展现了贵港的传统民居建筑和生活风貌，是了解贵港历史文化的重要窗口。",
      rating: 4.7,
      price: 0
    },
    {
      id: 5,
      name: "贵港荷花园",
      category: "water",
      coverImage: "https://img2.baidu.com/it/u=2326020106,645936319&fm=253&fmt=auto&app=120&f=JPEG?w=1539&h=800",
      description: "夏季荷花盛开，是拍摄荷花的绝佳地点，园内设有多个观景平台和休息区，是夏季避暑的好去处。",
      rating: 4.5,
      price: 30
    }
  ];
  spotsList.value = JSON.parse(JSON.stringify(allSpotsList.value.slice(0, pageSize.value)));
  totalCount.value = allSpotsList.value.length;
};

// 添加一个保存所有景点数据的数组
const allSpotsList = ref([]);

// 更新分页后的列表
const updatePagedList = () => {
  // 确保allSpotsList有数据
  if (allSpotsList.value.length === 0) {
    console.warn("警告: allSpotsList为空，无法分页显示数据");
    return;
  }
  
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  
  console.log("更新分页列表 - 参数:", {
    startIndex,
    endIndex,
    allSpotsList长度: allSpotsList.value.length,
    currentPage: currentPage.value,
    pageSize: pageSize.value
  });
  
  // 检查索引是否合法
  if (startIndex >= allSpotsList.value.length) {
    console.warn("起始索引超出范围，重置为0");
    currentPage.value = 1;
    spotsList.value = allSpotsList.value.slice(0, pageSize.value);
  } else {
    // 使用深拷贝确保数据能正确更新
    spotsList.value = JSON.parse(JSON.stringify(allSpotsList.value.slice(startIndex, endIndex)));
  }
  
  console.log("更新后的spotsList:", spotsList.value.map(item => item.name));
};

// 处理页面大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1; // 切换页面大小时重置到第一页
  updatePagedList(); // 更新显示的数据
};

// 处理页面变化
const handlePageChange = (page) => {
  currentPage.value = page;
  updatePagedList(); // 更新显示的数据
};

// 监听筛选器和搜索变化
watch([filters, searchQuery], () => {
  currentPage.value = 1; // 重置到第一页
  handleFilter(); // 重新加载数据
}, { deep: true });

// 获取景点分类和筛选选项
const fetchCategories = async () => {
  try {
    const res = await service.get('/public/spot/categories');
    console.log("分类数据API响应:", res);
    
    if (res.data && res.data.code === 200) {
      const apiData = res.data.data;
      
      // 直接是分类数组
      if (Array.isArray(apiData)) {
        categoryOptions.value = apiData.map(item => ({
          label: item.name,
          value: item.id
        }));
      } 
      // 分类数据在对象内
      else if (apiData && typeof apiData === 'object') {
        if (apiData.categories) {
          categoryOptions.value = apiData.categories.map(item => ({
            label: item.name,
            value: item.id
          }));
        }
        
        if (apiData.areas) {
          areaOptions.value = apiData.areas.map(item => ({
            label: item.name,
            value: item.id
          }));
        }
        
        if (apiData.tags) {
          tagOptions.value = apiData.tags.map(item => ({
            label: item.name,
            value: item.id
          }));
        }
      }
    }
  } catch (error) {
    console.error("获取分类数据失败:", error);
    // 使用默认数据，不显示错误提示
  }
};

// 选项数据
const categoryOptions = ref([
  { label: "自然风光", value: "nature" },
  { label: "人文古迹", value: "cultural" },
  { label: "主题乐园", value: "theme" },
  { label: "宗教寺庙", value: "religious" },
]);

const areaOptions = ref([
  { label: "港北区", value: "gangbei" },
  { label: "港南区", value: "gangnan" },
  { label: "覃塘区", value: "qintang" },
  { label: "平南县", value: "pingnan" },
  { label: "桂平市", value: "guiping" },
]);

const tagOptions = ref([
  { label: "网红打卡", value: "popular" },
  { label: "亲子游玩", value: "family" },
  { label: "情侣约会", value: "couple" },
  { label: "户外探险", value: "outdoor" },
  { label: "历史文化", value: "history" },
]);

const sortOptions = [
  { label: "评分最高", value: "rating" },
  { label: "人气最高", value: "popularity" },
  { label: "价格最低", value: "price_asc" },
  { label: "价格最高", value: "price_desc" },
];

// 已选筛选条件
const selectedFilters = computed(() => {
  const result = [];

  if (filters.value.category) {
    const category = categoryOptions.value.find(
      (item) => item.value === filters.value.category,
    );
    if (category) result.push(category);
  }

  if (filters.value.area) {
    const area = areaOptions.value.find((item) => item.value === filters.value.area);
    if (area) result.push(area);
  }

  filters.value.tags.forEach((tag) => {
    const tagOption = tagOptions.value.find((item) => item.value === tag);
    if (tagOption) result.push(tagOption);
  });

  return result;
});

// 视图模式
const viewMode = ref("grid");

// 分页相关
const currentPage = ref(1);
const pageSize = ref(4); // 将默认页面大小改为4
const totalCount = ref(0);

// 景点数据
const spotsList = ref([]);

// 地图相关
const mapCenter = ref([110.279121, 23.111471]); // 贵港市中心坐标
const mapZoom = ref(12);
const spotMarkers = computed(() => {
  return spotsList.value.map((spot) => ({
    id: spot.id,
    position: [spot.longitude, spot.latitude],
    title: spot.name,
  }));
});

// 分享相关
const shareDialogVisible = ref(false);
const shareContent = ref({});

// 攻略生成相关
const strategyDialogVisible = ref(false);
const currentSpot = ref(null);

// 路线规划相关
const routeDialogVisible = ref(false);
const selectedSpots = ref([]);

// 推荐景点数据
const recommendedSpots = ref([]);

// 获取推荐景点数据 - 也确保使用准确的图片字段
const fetchRecommendedSpots = () => {
  // 如果景点列表不为空，随机选择2个展示
  if (allSpotsList.value.length > 0) {
    // 复制一份列表数据，避免直接修改
    const spotsCopy = JSON.parse(JSON.stringify(allSpotsList.value));
    // 随机打乱数组
    spotsCopy.sort(() => Math.random() - 0.5);
    // 取前2个或全部(如果少于2个)
    recommendedSpots.value = spotsCopy.slice(0, Math.min(2, spotsCopy.length));
    
    // 确保cover字段和rating字段存在
    recommendedSpots.value.forEach(spot => {
      // 处理封面图片
      if (!spot.cover && spot.coverImage) {
        spot.cover = spot.coverImage;
      }
      
      // 处理评分 - 确保有评分数据
      if (!spot.rating || spot.rating === 0) {
        spot.rating = spot.rating || 4.5; // 如果评分为0或未定义，设置默认评分
      }
    });
    
    console.log("处理后的推荐景点数据:", recommendedSpots.value);
  } else {
    // 使用测试数据
    console.log("推荐景点使用测试数据 - 景点列表为空");
    recommendedSpots.value = [
      {
        id: 1,
        name: "贵港博物馆",
        cover: "https://img1.baidu.com/it/u=2689790312,1143352549&fm=253&fmt=auto&app=138&f=JPEG?w=1376&h=500",
        rating: 4.8,
        price: 0,
        description: "了解贵港历史文化的最佳去处，馆内收藏了大量珍贵文物。",
      },
      {
        id: 2,
        name: "贵港古镇",
        cover: "https://img0.baidu.com/it/u=2330699682,103157205&fm=253&fmt=auto&app=120&f=JPEG?w=1202&h=800",
        rating: 4.7,
        price: 0,
        description: "保存完好的古镇街区，展现了贵港的传统民居建筑和生活风貌。",
      },
    ];
  }
};

// 当前季节
const currentSeason = computed(() => {
  const month = new Date().getMonth() + 1;
  if (month >= 3 && month <= 5) return "春季";
  if (month >= 6 && month <= 8) return "夏季";
  if (month >= 9 && month <= 11) return "秋季";
  return "冬季";
});

// 季节性景点数据
const seasonalSpots = ref([]);

// 获取季节性景点 - 使用测试数据而不是API
const fetchSeasonalSpots = () => {
  // 不再调用API，直接使用测试数据
  console.log("使用季节性景点测试数据");
  seasonalSpots.value = [
    {
      id: 1,
      name: "贵港江滨公园",
      cover:
        "https://img0.baidu.com/it/u=1995709151,1000347016&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500",
      description: "春季百花盛开，是观赏花海的最佳时节。",
      bestTime: "3月-5月",
      suggestedTime: "2-3小时",
    },
    {
      id: 2,
      name: "贵港荷花园",
      cover:
        "https://img2.baidu.com/it/u=2326020106,645936319&fm=253&fmt=auto&app=120&f=JPEG?w=1539&h=800",
      description: "夏季荷花盛开，是拍摄荷花的绝佳地点。",
      bestTime: "6月-8月",
      suggestedTime: "1-2小时",
    },
  ];
};

// 方法
const removeFilter = (filter) => {
  if (filter.value === filters.value.category) {
    filters.value.category = "";
  } else if (filter.value === filters.value.area) {
    filters.value.area = "";
  } else {
    filters.value.tags = filters.value.tags.filter(
      (tag) => tag !== filter.value,
    );
  }
};

const getTagType = (tag) => {
  const tagTypes = {
    免费开放: "success",
    亲子游玩: "warning",
    休闲娱乐: "info",
    自然风光: "success",
    摄影胜地: "warning",
    网红打卡: "danger",
    历史文化: "info",
    室内景点: "info",
  };
  return tagTypes[tag] || "info";  // 默认返回"info"而不是"default"
};

const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

const viewSpotDetail = (id) => {
  router.push(`/spots/${id}`);
};

const toggleCollect = async (spot) => {
  try {
    // 调用收藏/取消收藏API (需要登录)
    if (!localStorage.getItem('token')) {
      ElMessage.warning('请先登录后再收藏');
      return;
    }
    
    const url = spot.isCollected ? '/spot/uncollect' : '/spot/collect';
    await service.post(url, { spotId: spot.id });
    
    spot.isCollected = !spot.isCollected;
    ElMessage.success(spot.isCollected ? "收藏成功" : "已取消收藏");
  } catch (error) {
    console.error("收藏操作失败:", error);
    ElMessage.error("操作失败，请重试");
  }
};

const shareSpot = (spot) => {
  shareContent.value = {
    title: spot.name,
    description: spot.description,
    image: spot.cover,
    url: window.location.origin + `/spots/${spot.id}`,
  };
  shareDialogVisible.value = true;
};

const handleShare = (data) => {
  console.log("分享数据：", data);
  ElMessage.success("分享成功");
};

const generateStrategy = (spot) => {
  currentSpot.value = spot;
  strategyDialogVisible.value = true;
};

const handleStrategySave = (data) => {
  console.log("保存攻略：", data);
  ElMessage.success("攻略已保存");
};

const handleMarkerClick = (marker) => {
  viewSpotDetail(marker.id);
};

// 刷新推荐
const refreshRecommendations = () => {
  // 重新从列表中随机选择
  fetchRecommendedSpots();
  ElMessage.success("推荐已更新");
};

// 路线规划相关方法
const isSpotSelected = (spot) => {
  return selectedSpots.value.some((s) => s.id === spot.id);
};

const toggleSpotSelection = (spot) => {
  const index = selectedSpots.value.findIndex((s) => s.id === spot.id);
  if (index > -1) {
    selectedSpots.value.splice(index, 1);
  } else {
    selectedSpots.value.push(spot);
  }
};

// 路线规划地图实例
let routeMap = null;
let routingPolicy = 0; // 默认驾车导航策略
let routePlanner = null;

// 路线规划对话框相关方法
const showRoutePlanner = () => {
  if (selectedSpots.value.length === 0) {
    ElMessage.warning("请先选择要游览的景点");
    return;
  }
  
  // 重置路线规划相关变量
  routeMap = null;
  routePlanner = null;
  
  // 显示路线规划对话框
  routeDialogVisible.value = true;
  
  console.log("打开路线规划对话框，选择的景点数:", selectedSpots.value.length);
};

// 路线地图准备完成回调
const handleRouteMapReady = (mapInstance) => {
  console.log("路线规划地图已加载完成", mapInstance);
  routeMap = mapInstance;
  
  // 确保已选择了景点
  if (selectedSpots.value.length > 0) {
    // 延迟一小段时间再初始化路线规划，确保地图完全加载
    setTimeout(() => {
      initRoutePlanner();
    }, 500);
  }
};

// 初始化路线规划器
const initRoutePlanner = () => {
  if (!routeMap || !AMap || selectedSpots.value.length === 0) return;
  
  try {
    // 清除之前的路线
    routeMap.clearMap();
    
    // 加载驾车路线规划插件
    AMap.plugin(['AMap.Driving', 'AMap.Walking', 'AMap.Transfer'], () => {
      // 默认使用驾车规划
      routePlanner = new AMap.Driving({
        map: routeMap,
        panel: 'route-result-panel', // 结果面板的ID
        policy: routingPolicy, // 默认策略
        hideMarkers: false,
        showTraffic: true,
        autoFitView: true
      });
      
      // 规划路线
      planRoute();
    });
  } catch (error) {
    console.error("初始化路线规划器失败:", error);
    ElMessage.error("路线规划功能加载失败，请重试");
  }
};

// 规划路线
const planRoute = async () => {
  if (!routePlanner || selectedSpots.value.length === 0) return;

  try {
    // 显示加载中
    ElMessage.info("正在规划路线...");
    
    // 准备起点、途经点和终点
    const spots = [...selectedSpots.value];
    
    if (spots.length === 1) {
      // 只有一个景点，从用户当前位置到该景点
      // 尝试获取用户当前位置
      getCurrentPosition().then(position => {
        const startPoint = position ? new AMap.LngLat(position[0], position[1]) : new AMap.LngLat(109.613196, 23.103333);
        
        // 目的地：通过景点名称搜索获取位置
        searchSpotLocation(spots[0].name).then(endPosition => {
          if (endPosition) {
            const endPoint = new AMap.LngLat(endPosition[0], endPosition[1]);
            
            // 规划路线
            routePlanner.search(startPoint, endPoint, (status, result) => {
              handleRouteResult(status, result);
            });
          } else {
            ElMessage.error(`无法找到景点"${spots[0].name}"的位置`);
          }
        });
      });
    } else {
      // 多个景点，第一个为起点，最后一个为终点，中间的为途经点
      const promises = spots.map(spot => searchSpotLocation(spot.name));
      
      // 等待所有位置搜索完成
      Promise.all(promises).then(positions => {
        // 过滤掉未找到位置的景点
        const validPositions = positions.filter(p => p !== null);
        
        if (validPositions.length < 2) {
          ElMessage.error("无法找到足够的景点位置信息");
          return;
        }
        
        // 获取起点、终点
        const startPoint = new AMap.LngLat(validPositions[0][0], validPositions[0][1]);
        const endPoint = new AMap.LngLat(validPositions[validPositions.length - 1][0], validPositions[validPositions.length - 1][1]);
        
        // 如果有途经点
        let waypoints = [];
        if (validPositions.length > 2) {
          waypoints = validPositions.slice(1, validPositions.length - 1).map(
            p => new AMap.LngLat(p[0], p[1])
          );
        }
        
        // 规划路线
        routePlanner.search(
          startPoint, 
          endPoint, 
          { waypoints: waypoints },
          (status, result) => {
            handleRouteResult(status, result);
          }
        );
      });
    }
  } catch (error) {
    console.error("规划路线失败:", error);
    ElMessage.error("路线规划失败，请重试");
  }
};

// 处理路线规划结果
const handleRouteResult = (status, result) => {
  if (status === 'complete') {
    ElMessage.success("路线规划成功");
  } else {
    console.error("路线规划失败:", result);
    ElMessage.error("路线规划失败，可能是景点位置信息不准确");
  }
};

// 获取当前位置
const getCurrentPosition = () => {
  return new Promise((resolve) => {
    if (!AMap) {
      resolve(null);
      return;
    }
    
    try {
      AMap.plugin('AMap.Geolocation', () => {
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
          zoomToAccuracy: true
        });
        
        geolocation.getCurrentPosition((status, result) => {
          if (status === "complete") {
            resolve([result.position.lng, result.position.lat]);
          } else {
            console.warn("获取当前位置失败:", result);
            resolve(null);
          }
        });
      });
    } catch (error) {
      console.error("获取当前位置失败:", error);
      resolve(null);
    }
  });
};

// 搜索景点位置
const searchSpotLocation = (spotName) => {
  return new Promise((resolve) => {
    if (!AMap) {
      resolve(null);
      return;
    }
    
    try {
      AMap.plugin('AMap.PlaceSearch', () => {
        // 创建搜索实例
        const placeSearch = new AMap.PlaceSearch({
          city: '贵港',
          citylimit: true
        });
        
        // 为搜索添加城市名以提高准确性
        const searchKeyword = spotName.includes('贵港') ? spotName : `贵港${spotName}`;
        
        // 搜索位置
        placeSearch.search(searchKeyword, (status, result) => {
          if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
            // 获取第一个搜索结果的位置
            const position = [
              result.poiList.pois[0].location.lng,
              result.poiList.pois[0].location.lat
            ];
            resolve(position);
          } else {
            console.warn(`未找到景点位置: ${spotName}`);
            resolve(null);
          }
        });
      });
    } catch (error) {
      console.error("搜索景点位置失败:", error);
      resolve(null);
    }
  });
};

// 切换路线规划方式 (驾车/步行/公交)
const changeRoutingMode = (mode) => {
  if (!routeMap || !AMap) return;
  
  try {
    // 清除之前的路线
    routeMap.clearMap();
    
    // 根据模式创建不同的规划器
    if (mode === 'driving') {
      routePlanner = new AMap.Driving({
        map: routeMap,
        panel: 'route-result-panel',
        policy: routingPolicy,
        hideMarkers: false,
        showTraffic: true
      });
    } else if (mode === 'walking') {
      routePlanner = new AMap.Walking({
        map: routeMap,
        panel: 'route-result-panel',
        hideMarkers: false
      });
    } else if (mode === 'transit') {
      routePlanner = new AMap.Transfer({
        map: routeMap,
        panel: 'route-result-panel',
        policy: 0, // 最快捷模式
        hideMarkers: false,
        city: '贵港'
      });
    }
    
    // 重新规划路线
    planRoute();
  } catch (error) {
    console.error("切换路线规划方式失败:", error);
    ElMessage.error("切换路线规划方式失败");
  }
};

// 切换驾车路线规划策略
const changeRoutingPolicy = (policy) => {
  routingPolicy = policy;
  
  // 如果是驾车导航，更新策略并重新规划
  if (routePlanner instanceof AMap.Driving) {
    routePlanner.setPolicy(policy);
    planRoute();
  }
};

const handleRouteSave = async (route) => {
  try {
    // 保存路线到用户收藏 (需要登录)
    if (!localStorage.getItem('token')) {
      ElMessage.warning('请先登录后再保存路线');
      return;
    }
    
    // 获取当前规划的路线信息
    const routeInfo = {
      ...route,
      spots: selectedSpots.value.map(s => ({
        id: s.id,
        name: s.name
      }))
    };
    
    await service.post('/route/save', routeInfo);
    ElMessage.success("路线已保存");
  } catch (error) {
    console.error("保存路线失败:", error);
    ElMessage.error("保存失败，请重试");
  }
};

// 添加事件处理函数
const handleAddToRoute = (spot) => {
  if (spot) {
    selectedSpots.value.push(spot);
    ElMessage.success(`已将${spot.name}添加到路线`);
  }
};

// 页面初始化
onMounted(() => {
  fetchCategories();      // 获取分类数据
  
  // 获取景点列表数据
  handleFilter().then(() => {
    console.log("页面加载完成后的数据状态:", {
      所有景点数量: allSpotsList.value.length,
      当前页景点数量: spotsList.value.length
    });
    
    // 如果有数据但spotsList为空，尝试强制更新
    if (allSpotsList.value.length > 0 && spotsList.value.length === 0) {
      console.log("检测到数据异常，尝试强制更新视图...");
      // 1秒后强制更新一次
      setTimeout(() => {
        updatePagedList();
        console.log("强制更新后:", spotsList.value);
      }, 1000);
    }
    
    // 确保有数据后，从列表中选择推荐
    if (allSpotsList.value.length > 0) {
      fetchRecommendedSpots();  // 从列表中选择推荐景点
    }
  });  
  
  fetchSeasonalSpots();    // 获取季节性景点
  
  // 打印一些调试信息
  console.log("页面初始化 - 分页设置:", {
    当前页: currentPage.value,
    页面大小: pageSize.value
  });
});

// 在script setup部分添加获取分类名称的方法
const getCategoryName = (categoryValue) => {
  // 先从选项中查找
  const category = categoryOptions.value.find(
    (item) => item.value === categoryValue
  );
  
  if (category) return category.label;
  
  // 如果选项中没有，使用默认映射
  const defaultCategories = {
    'nature': '自然风光',
    'cultural': '人文古迹',
    'historical': '历史文化',
    'theme': '主题乐园',
    'religious': '宗教寺庙',
    'water': '水上景观',
    'museum': '博物馆',
    'park': '公园',
    'garden': '花园',
  };
  
  return defaultCategories[categoryValue] || categoryValue;
};
</script>

<style lang="scss" scoped>
.spots-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .page-header {
    @apply bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 shadow-sm;

    h1 {
      @apply text-gray-900 dark:text-white;
    }

    p {
      @apply text-gray-600 dark:text-gray-400;
    }

    .back-btn {
      @apply hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-gray-200 transition-colors;
    }
  }

  .filter-toolbar {
    @apply bg-white dark:bg-gray-800 transition-all duration-300
           border border-gray-200 dark:border-gray-700
           shadow-[0_2px_12px_0_rgba(0,0,0,0.1)] dark:shadow-[0_2px_12px_0_rgba(0,0,0,0.3)];

    &:hover {
      @apply shadow-[0_4px_20px_0_rgba(0,0,0,0.15)] dark:shadow-[0_4px_20px_0_rgba(0,0,0,0.4)];
    }

    .search-bar {
      .search-input {
        :deep(.el-input__wrapper) {
          height: 36px;
          border: 1px solid #e5e7eb;
          border-radius: 4px;
          transition: all 0.3s ease;
          background-color: white;

          &:hover {
            border-color: #d1d5db;
          }

          &.is-focus {
            border-color: var(--el-color-primary);
            box-shadow: 0 0 0 1px var(--el-color-primary-light-2);
          }

          @apply dark:bg-gray-800 dark:border-gray-700 dark:hover:border-gray-600;

          &.is-focus {
            @apply dark:border-primary-500 dark:hover:border-primary-400;
          }
        }

        :deep(.el-input__inner) {
          height: 36px;
          line-height: 36px;
          @apply dark:text-gray-200 dark:bg-gray-800;
        }

        :deep(.el-input__prefix) {
          color: #9ca3af;
          font-size: 16px;
          transition: color 0.3s ease;
          @apply dark:text-gray-400;
        }

        &:hover {
          :deep(.el-input__prefix) {
            color: var(--el-color-primary);
            @apply dark:text-gray-300;
          }
        }
      }
    }

    .filter-item {
      :deep(.el-select) {
        .el-input__wrapper {
          @apply dark:bg-gray-800 dark:border-gray-700 dark:hover:border-gray-600;

          &.is-focus {
            @apply dark:border-primary-500 dark:hover:border-primary-400;
          }
        }

        .el-input__inner {
          @apply dark:text-gray-200 dark:bg-gray-800;
        }

        .el-input__prefix {
          @apply dark:text-gray-400;
        }
      }
    }

    .selected-filters {
      :deep(.el-tag) {
        @apply dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200;

        .el-tag__close {
          @apply dark:text-gray-400 dark:hover:text-gray-200 dark:hover:bg-gray-600;
        }
      }
    }
  }

  .spot-card {
    @apply bg-white dark:bg-gray-800 cursor-pointer 
           border border-gray-200 dark:border-gray-700
           shadow-[0_2px_12px_0_rgba(0,0,0,0.1)] dark:shadow-[0_2px_12px_0_rgba(0,0,0,0.3)]
           transition-all duration-300;

    &:hover {
      @apply transform -translate-y-1
             shadow-[0_4px_20px_0_rgba(0,0,0,0.15)] dark:shadow-[0_4px_20px_0_rgba(0,0,0,0.4)]
             border-gray-300 dark:border-gray-600;
    }

    h3 {
      @apply text-gray-900 dark:text-white transition-colors duration-300
             hover:text-primary-600 dark:hover:text-primary-400;
    }

    .spot-desc {
      @apply text-gray-600 dark:text-gray-400;
    }

    .spot-meta {
      @apply text-gray-500 dark:text-gray-400;

      .el-icon {
        @apply text-gray-400 dark:text-gray-500;
      }
    }

    .card-actions {
      @apply border-t border-gray-100 dark:border-gray-700;
    }

    .spot-tags {
      :deep(.el-tag) {
        @apply dark:border-opacity-50;

        &.el-tag--success {
          @apply dark:bg-green-900/30 dark:text-green-300 dark:border-green-700;
        }

        &.el-tag--warning {
          @apply dark:bg-yellow-900/30 dark:text-yellow-300 dark:border-yellow-700;
        }

        &.el-tag--danger {
          @apply dark:bg-red-900/30 dark:text-red-300 dark:border-red-700;
        }

        &.el-tag--info {
          @apply dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600;
        }

        &.el-tag--default {
          @apply dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600;
        }
      }
    }
  }

  .recommended-spots,
  .seasonal-spots {
    @apply bg-white dark:bg-gray-800 
           border border-gray-200 dark:border-gray-700
           shadow-[0_2px_12px_0_rgba(0,0,0,0.1)] dark:shadow-[0_2px_12px_0_rgba(0,0,0,0.3)];

    h3 {
      @apply text-gray-900 dark:text-white;
    }

    .recommended-item {
      @apply hover:bg-gray-50 dark:hover:bg-gray-700/50;

      .font-medium {
        @apply text-gray-900 dark:text-white;
      }

      .description {
        @apply text-gray-500 dark:text-gray-400;
      }
    }

    .seasonal-item {
      @apply bg-gray-50 dark:bg-gray-700/50 border-gray-100 dark:border-gray-700;

      h4 {
        @apply text-gray-900 dark:text-white;
      }

      p {
        @apply text-gray-600 dark:text-gray-400;
      }

      .meta-info {
        @apply text-gray-500 dark:text-gray-400;
      }
    }
  }

  :deep(.el-pagination) {
    @apply dark:bg-transparent;

    .el-pagination__total {
      @apply dark:text-gray-400;
    }

    .el-pagination__jump {
      @apply dark:text-gray-400;
    }

    .el-input__inner {
      @apply dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600;
    }

    button {
      @apply dark:bg-transparent dark:text-gray-400;

      &:disabled {
        @apply dark:text-gray-600;
      }
    }

    .el-pager li {
      @apply dark:bg-transparent dark:text-gray-400;

      &.active {
        @apply dark:text-primary-500;
      }
    }
  }

  .view-controls {
    .total-count {
      @apply text-gray-600 dark:text-gray-400;
    }
  }

  .image-slot {
    @apply bg-gray-100 dark:bg-gray-700 flex items-center justify-center;

    .el-icon {
      @apply text-gray-400 dark:text-gray-500;
    }
  }
}
</style>
